package com.ruoyi.web.controller.system;

import java.util.List;

import com.ruoyi.activiti.ActivitiCompleteTask;
import com.ruoyi.activiti.ActivitiTaskQuery;
import com.ruoyi.activitidemo.ProcessController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ActivitiLeave;
import com.ruoyi.system.service.IActivitiLeaveService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 工作流demo：请假申请Controller
 * 
 * @author ruoyi
 * @date 2022-03-04
 */
@Controller
@RequestMapping("/system/leave")
public class ActivitiLeaveController extends BaseController
{
    private String prefix = "system/leave";

    @Autowired
    private IActivitiLeaveService activitiLeaveService;

    //yanruTODO 测试 工作流请假测试
    @Autowired
    private ProcessController processController;

    @RequiresPermissions("system:leave:view")
    @GetMapping()
    public String leave()
    {
        return prefix + "/leave";
    }

    @Autowired
    private SysUserServiceImpl userService;
    /**
     * 查询工作流demo：请假申请列表
     */
    @RequiresPermissions("system:leave:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ActivitiLeave activitiLeave)
    {
        startPage();
        List<ActivitiLeave> list = activitiLeaveService.selectActivitiLeaveList(activitiLeave);

        //初始化每个请假单信息
        for(ActivitiLeave temp :list) {
            Task task = ActivitiTaskQuery.queryTask(temp);

            logger.debug("初始化审批id="+temp.getId()+",user="+temp.getUserName()+",task不为空?"+(task!=null)
            +",assign="+(task!=null? task.getAssignee():""));
            if(task != null)
            {
                SysUser user=                this.userService.selectUserById(Long.valueOf(task.getAssignee()));

                temp.setStateStr("等待用户id"+task.getAssignee()+"["+user.getLoginName()+"]操作(任务id:"+
                        task.getId() + ")");
            }
            else {
                temp.setStateStr("已完结");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出工作流demo：请假申请列表
     */
    @RequiresPermissions("system:leave:export")
    @Log(title = "工作流demo：请假申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ActivitiLeave activitiLeave)
    {
        List<ActivitiLeave> list = activitiLeaveService.selectActivitiLeaveList(activitiLeave);
        ExcelUtil<ActivitiLeave> util = new ExcelUtil<ActivitiLeave>(ActivitiLeave.class);
        return util.exportExcel(list, "工作流demo：请假申请数据");
    }

    /**
     * 新增工作流demo：请假申请
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存工作流demo：请假申请
     */
    @RequiresPermissions("system:leave:add")
    @Log(title = "工作流demo：请假申请", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ActivitiLeave activitiLeave)
    {
        activitiLeave.setUserId(getUserId());
        activitiLeave.setUserName(getLoginName());


//        activitiLeave.setu
        logger.debug("收到添加请假="+activitiLeave);

        int res = activitiLeaveService.insertActivitiLeave(activitiLeave);
        //yanruTODO 更新工作流
        this.processController.addInstance(getSysUser(), activitiLeave);

        return toAjax(res);
    }


    ///审批操作
    @PostMapping("/complete")
    @ResponseBody
    public AjaxResult complete(ActivitiLeave activitiLeave)
    {
        Long id = activitiLeave.getId();
        //操作类型
        Long type = activitiLeave.getUserId();

        //        activitiLeave.setUserId(getUserId());
        logger.debug("收到审批操作="+id+",操作类型="+type);


        //查询任务
        Task task = ActivitiTaskQuery.queryTask(activitiLeave);
        if(!task.getAssignee().equals(getUserId()+"")) {
            SysUser user = userService.selectUserById(Long.valueOf(task.getAssignee()));
            return error("非该节点的审批人，该节点的实际审批人应当为:" + user.getLoginName());
        }

        logger.debug("我是审批负责人，执行任务");

//        //查询任务
//        Task task = ActivitiTaskQuery.queryTask(activitiLeave);
//

        SysUser nextUser = userService.selectUserByLoginName("总经理王晓晓");// ShiroUtils.getSysUser();
        System.out.println("指定下一个审批负责人user=" + nextUser.getLoginName());

//        //完成任务
          ActivitiCompleteTask.complete(task, nextUser);

        //完成任务
        //  ActivitiCompleteTask.complete(task);

//        int res = 0;activitiLeaveService.insertActivitiLeave(activitiLeave);
//        //yanruTODO 更新工作流
//        this.processController.addInstance(getSysUser(), activitiLeave);

     //   return toAjax(res);
        return success();
    }

    /**
     * 修改工作流demo：请假申请
     */
    @RequiresPermissions("system:leave:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ActivitiLeave activitiLeave = activitiLeaveService.selectActivitiLeaveById(id);
        mmap.put("activitiLeave", activitiLeave);
        return prefix + "/edit";
    }

    /**
     * 修改保存工作流demo：请假申请
     */
    @RequiresPermissions("system:leave:edit")
    @Log(title = "工作流demo：请假申请", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ActivitiLeave activitiLeave)
    {
        return toAjax(activitiLeaveService.updateActivitiLeave(activitiLeave));
    }

    /**
     * 删除工作流demo：请假申请
     */
    @RequiresPermissions("system:leave:remove")
    @Log(title = "工作流demo：请假申请", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String[] idsarray = ids.split(",");
        for(String temp:idsarray)
        {
            ActivitiLeave activitiLeave =  this.activitiLeaveService.selectActivitiLeaveById(Long.valueOf(temp));
            if(activitiLeave!=null)
            {
                //yanruTODO 检查删除流程定义
                System.out.println("检查删除流程定义");
            }
        }

        return toAjax(activitiLeaveService.deleteActivitiLeaveByIds(ids));
    }


    /**
     * demo的工作流 请假页面，
     * @return
     */
    @GetMapping("/leaveindex/{id}")
    public String leaveindex(@PathVariable("id") Long id, ModelMap mmap)
    {
        ActivitiLeave activitiLeave = activitiLeaveService.selectActivitiLeaveById(id);
        mmap.put("activitiLeave", activitiLeave);
        logger.debug("查看指定工作流数据="+id+",activitiLeave="+activitiLeave);
        return prefix + "/leaveindex";
    }

    //请求获取我提交的请假

}
